# def gen_data():
#     data_list = []
#     # 模拟在data_list中添加一百万条数据
#     for i in range(1000000):
#         data_list.append(i)
#     return  data_list

def gen_data():
    # 生成器函数
    # 模拟在data_list中添加一百万条数据
    for i in range(10):
        yield i


# 生成器对象
data_lst = gen_data()


# print(data_lst) # <generator object gen_data at 0x10545c820>
# for data in data_lst:
#     print(data)

def test(num):
    while num > 0:
        # yield num # 每次获取num 函数都会在此处暂停
        t = yield num  # t 是生成器对象send进来的
        if t is not None:
            return
        num -= 1


# gen = test(5)
# # num = next(gen) # 等价于gen.send(None)
# num = gen.send(None)
# print(num)
# num = gen.send(10)
# print(num)
# num = next(gen)
# print(num)
# for g in gen:
#     # for 循环的底层实现其实也是不断的next(gen)
#     print(g)

# 生成器实现斐波那契数列
# 1 1 2 3 5 8 13
def gen_fib(num):
    a, b = 0, 1
    while num:
        yield b
        a, b = b, a + b
        num -= 1

fib = gen_fib(5)
for i in fib:
    print(i)


"""
生成器表达式
和列表推导式一样的写法，将中括号改成圆括号，在不需要一次性生成所有值的场景下使用
"""

even_numbers = (x for x in range(1,10) if x % 2 == 0)
for even in even_numbers:
    print(even)